<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item label="所属会员" prop="memberName">
              <el-input v-model="queryParams.memberName" placeholder="请输入会员名称" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="订单号" prop="orderNumber">
              <el-input v-model="queryParams.orderNumber" placeholder="请输入订单号" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="状态" prop="status">
              <el-select v-model="queryParams.status" placeholder="订单状态" clearable>
                <el-option v-for="dict in commodity_status" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="创建时间" style="width: 308px">
              <el-date-picker
                v-model="dateRangeCreateTime"
                value-format="YYYY-MM-DD HH:mm:ss"
                type="daterange"
                range-separator="-"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                :default-time="[new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 1, 1, 23, 59, 59)]"
              ></el-date-picker>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button v-hasPermi="['system:goodsOrder:remove']" type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()"
              >删除
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button v-hasPermi="['system:goodsOrder:export']" type="warning" plain icon="Download" @click="handleExport">导出 </el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @query-table="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" :data="goodsOrderList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column v-if="true" label="id" align="center" prop="id" />
        <el-table-column label="订单编号" align="center" prop="orderNumber" />
        <el-table-column label="所属会员" align="center" prop="memberName" />
        <el-table-column label="收货地址" align="center" prop="fullAddress" />
        <el-table-column label="总金额" align="center" prop="totalPrice" />
        <el-table-column label="支付金额" align="center" prop="payPrice" />
        <el-table-column label="创建时间" align="center" prop="createTime" width="155">
          <template #default="scope">
            <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d} {h}:{i}:{s} ') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="支付时间" align="center" prop="payTime" width="155">
          <template #default="scope">
            <span>{{ parseTime(scope.row.payTime, '{y}-{m}-{d} {h}:{i}:{s} ') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="状态" align="center" prop="status">
          <template #default="scope">
            <dict-tag :options="commodity_status" :value="scope.row.status" />
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip content="详情" placement="top">
              <el-button v-hasPermi="['system:goodsOrder:view']" link type="primary" icon="View" @click="handleDetail(scope.row)"></el-button>
            </el-tooltip>
            <el-tooltip content="发货" placement="top">
              <el-button
                v-hasPermi="['system:goodsOrder:delivery']"
                link
                type="primary"
                icon="Position"
                @click="handleDelivery(scope.row)"
              ></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button v-hasPermi="['system:goodsOrder:remove']" link type="primary" icon="Delete" @click="handleDelete(scope.row)"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" :total="total" @pagination="getList" />
    </el-card>
    <!-- 商城订单详情 -->
    <el-dialog v-model="dialog.visible" :title="dialog.title" width="50%" append-to-body>
      <el-form ref="goodsOrderFormRef" :model="form" :rules="rules" label-width="80px">
        <el-descriptions :column="2" title="基本信息" border>
          <el-descriptions-item label="会员名称" label-class-name="my-label-class">
            {{ form.memberName }}
          </el-descriptions-item>
          <el-descriptions-item label="订单号" label-class-name="my-label-class">
            {{ form.orderNumber }}
          </el-descriptions-item>
          <el-descriptions-item label="总金额" label-class-name="my-label-class">
            {{ form.totalPrice }}
          </el-descriptions-item>
          <el-descriptions-item label="支付金额" label-class-name="my-label-class">
            {{ form.payPrice }}
          </el-descriptions-item>
          <el-descriptions-item label="创建时间" label-class-name="my-label-class">
            {{ form.createTime }}
          </el-descriptions-item>
          <el-descriptions-item label="支付时间" label-class-name="my-label-class">
            {{ form.payTime }}
          </el-descriptions-item>
          <el-descriptions-item label="收货地址" label-class-name="my-label-class" :span="2">
            {{ form.fullAddress }}
          </el-descriptions-item>
          <el-descriptions-item label="快递公司" label-class-name="my-label-class">
            {{ logisticsCompany.find((item) => item.dvyId === form.logisticsCompanyId)?.dvyName }}
          </el-descriptions-item>
          <el-descriptions-item label="快递单号" label-class-name="my-label-class">
            {{ form.logisticsNo }}
          </el-descriptions-item>
          <el-descriptions-item label="状态" label-class-name="my-label-class">
            <template #default="scope">
              <dict-tag :options="commodity_status" :value="form.status" />
            </template>
          </el-descriptions-item>
          <el-descriptions-item label="运费" label-class-name="my-label-class">
            {{ form.carriage }}
          </el-descriptions-item>
        </el-descriptions>
        <div>
          <h2>商品详情</h2>
          <el-collapse accordion>
            <el-collapse-item v-for="(detail, index) in form.goodsOrderDetails" :key="index">
              <template #title>
                <div class="count-right">
                  <div class="title-container">
                    <span>{{ detail.goods.title }}</span>
                  </div>
                  <span class="count">数量：{{ detail.count }}</span>
                </div>
              </template>
              <el-table :data="[detail.goods]" border style="width: 100%">
                <el-table-column prop="title" label="商品名称" width="350"></el-table-column>
                <el-table-column prop="price" label="售价" width="120"></el-table-column>
                <el-table-column label="商品图片">
                  <template #default="scope">
                    <el-image :src="scope.row.photoUrl.split(',')[0]" style="width: 100px; height: 100px"></el-image>
                  </template>
                </el-table-column>
              </el-table>
            </el-collapse-item>
          </el-collapse>
        </div>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cancel">关 闭</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 发货 -->
    <el-dialog v-model="deliveryDialog.visible" :title="deliveryDialog.title" width="500px" append-to-body>
      <!-- 下拉框获取快递公司 -->
      <div style="display: flex; align-items: center; margin-bottom: 10px">
        <span style="margin-right: 1.5%; width: 21%">快递公司：</span>
        <el-select v-model="form.logisticsCompanyId" placeholder="请选择快递公司">
          <el-option v-for="item in logisticsCompany" :key="item.dvyId" :label="item.dvyName" :value="item.dvyId" />
        </el-select>
      </div>
      <div style="display: flex; align-items: center">
        <span style="margin-right: 10px">快递单号：</span>
        <el-form ref="goodsOrderFormRef" v-model="form.logisticsNo" :model="form" :rules="rules" label-width="80px">
          <el-input v-model="form.logisticsNo" placeholder="请输入快递单号" />
        </el-form>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitDeliveryForm">确 定</el-button>
          <el-button @click="cancelDelivery">关 闭</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="GoodsOrder" lang="ts">
import { listGoodsOrder, getGoodsOrder, delGoodsOrder, addGoodsOrder, updateGoodsOrder, updateGoodsOrderDelivery } from '@/api/system/goodsOrder';
import { GoodsOrderVO, GoodsOrderQuery, GoodsOrderForm } from '@/api/system/goodsOrder/types';
import { allList } from '@/api/system/delivery';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { commodity_status } = toRefs<any>(proxy?.useDict('commodity_status'));
const goodsOrderList = ref<GoodsOrderVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const dateRangeCreateTime = ref<[DateModelType, DateModelType]>(['', '']);
const queryFormRef = ref<ElFormInstance>();
const goodsOrderFormRef = ref<ElFormInstance>();
const logisticsCompany = ref([]);
const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const deliveryDialog = reactive<DialogOption>({
  visible: false,
  title: ''
});
const initFormData: GoodsOrderForm = {
  id: undefined,
  memberId: undefined,
  totalPrice: undefined,
  payPrice: undefined,
  payTime: undefined,
  addressId: undefined,
  logisticsNo: undefined,
  logisticsCompanyId: undefined,
  orderNumber: undefined,
  status: undefined,
  carriage: undefined
};

const data = reactive<PageData<GoodsOrderForm, GoodsOrderQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    memberId: undefined,
    totalPrice: undefined,
    payPrice: undefined,
    payTime: undefined,
    addressId: undefined,
    logisticsNo: undefined,
    logisticsCompanyId: undefined,
    orderNumber: undefined,
    status: undefined,
    carriage: undefined,
    params: {}
  },
  rules: {
    id: [{ required: true, message: 'id不能为空', trigger: 'blur' }],
    memberId: [{ required: true, message: '会员id不能为空', trigger: 'blur' }],
    totalPrice: [{ required: true, message: '总金额不能为空', trigger: 'blur' }],
    payPrice: [{ required: true, message: '支付金额不能为空', trigger: 'blur' }],
    payTime: [{ required: true, message: '支付时间不能为空', trigger: 'blur' }],
    addressId: [{ required: true, message: '地址id不能为空', trigger: 'blur' }],
    logisticsNo: [{ required: true, message: '单号不能为空', trigger: 'blur' }],
    logisticsCompanyId: [{ required: true, message: '快递公司不能为空', trigger: 'blur' }],
    orderNumber: [{ required: true, message: '订单号不能为空', trigger: 'blur' }],
    status: [{ required: true, message: '状态不能为空', trigger: 'change' }],
    carriage: [{ required: true, message: '运费不能为空', trigger: 'blur' }]
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询商城订单列表 */
const getList = async () => {
  loading.value = true;
  const res = await listGoodsOrder(proxy?.addDateRange(queryParams.value, dateRangeCreateTime.value, 'CreateTime'));
  goodsOrderList.value = res.rows;
  total.value = res.total;
  loading.value = false;
};
// 获取快递公司
const getLogisticsCompany = async () => {
  const res = await allList();
  logisticsCompany.value = res.data;
};
/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
};

/** 取消按钮 */
const cancelDelivery = () => {
  reset();
  deliveryDialog.visible = false;
};
/** 表单重置 */
const reset = () => {
  form.value = { ...initFormData };
  goodsOrderFormRef.value?.resetFields();
};

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  dateRangeCreateTime.value = ['', ''];
  handleQuery();
};

/** 多选框选中数据 */
const handleSelectionChange = (selection: GoodsOrderVO[]) => {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
};

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  dialog.visible = true;
  dialog.title = '添加商城订单';
};
/** 详情按钮操作 */
const handleDetail = async (row?: GoodsOrderVO) => {
  reset();
  const _id = row?.id || ids.value[0];
  const res = await getGoodsOrder(_id);
  Object.assign(form.value, res.data);
  dialog.visible = true;
  dialog.title = '商城订单详情';
};

/** 发货 */
const handleDelivery = async (row?: GoodsOrderVO) => {
  reset();
  const _id = row?.id || ids.value[0];
  const res = await getGoodsOrder(_id);
  await getLogisticsCompany();
  Object.assign(form.value, res.data);
  deliveryDialog.visible = true;
  deliveryDialog.title = '发货';
};

/** 提交按钮 */
const submitForm = () => {
  goodsOrderFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.id) {
        await updateGoodsOrder(form.value).finally(() => (buttonLoading.value = false));
      } else {
        await addGoodsOrder(form.value).finally(() => (buttonLoading.value = false));
      }
      proxy?.$modal.msgSuccess('操作成功');
      dialog.visible = false;
      await getList();
    }
  });
};
/** 确认发货 */
const submitDeliveryForm = () => {
  goodsOrderFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;

      await updateGoodsOrderDelivery(form.value).finally(() => (buttonLoading.value = false));

      proxy?.$modal.msgSuccess('操作成功');
      dialog.visible = false;
      await getList();
    }
  });
};
/** 删除按钮操作 */
const handleDelete = async (row?: GoodsOrderVO) => {
  const _ids = row?.id || ids.value;
  await proxy?.$modal.confirm('是否确认删除商城订单编号为"' + _ids + '"的数据项？').finally(() => (loading.value = false));
  await delGoodsOrder(_ids);
  proxy?.$modal.msgSuccess('删除成功');
  await getList();
};

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download(
    'system/goodsOrder/export',
    {
      ...queryParams.value
    },
    `goodsOrder_${new Date().getTime()}.xlsx`
  );
};

onMounted(() => {
  getList();
});
</script>

<style scoped>
.title-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.count {
  //position: absolute;
  right: 0;
  top: 50%;
  //transform: translateY(-50%);
}

.count-right {
  display: flex;
  justify-content: space-between;
  width: 100%;
}
</style>
